package com.example.demo.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.example.demo.bean.CmsArticle;
import com.example.demo.bean.CmsCategory;
import com.example.demo.mapper.CmsArticleMapper;
import com.example.demo.mapper.CmsCategoryMapper;


@Service
public class CmsArticleService {
	@Autowired
	private CmsArticleMapper articleMapper;
	
	@Autowired
	private CmsCategoryMapper categoryMapper;
	
	//文章状态更新
	public boolean updateState(String artId,String state) {
		int result=articleMapper.updateStateById(artId, state);
		if(result==0) {
			return false;
		}
		return true;
	}
	
	
	//获取所有文章栏目信息	
	public List <CmsArticle> getAllArticle(){
		//List <CmsArticle> list =articleMapper.selectAll();
		List <CmsArticle> list =articleMapper.allArticleWithParent();
		if(list!=null) {                
			return list;
		}
		return new ArrayList<CmsArticle>();
	}

	//更新或者插入
	public boolean saveOrUpdateCmsArticle(String id,String title,String author,String categoryId) {
		
		if(categoryId!=null&&!"".equals(categoryId)){
			CmsCategory c =
			categoryMapper.selectByPrimaryKey(categoryId);
		
		if(c==null) {
			return false;
		}
		}
		if(id ==null||"".equals(id)) {
			CmsArticle art =new CmsArticle();
			art.setId(UUID.randomUUID().toString());
			art.setTitle(title);
			art.setMemberName(author);
			art.setCategoryId(categoryId);
			art.setPublishDate(new Date());
			art.setStatus("待审核");
			art.setReadNum(0);
			articleMapper.insert(art);
			
			
		}else {
			//如果用户传递了文章编号，代表需要更新文章信息
			CmsArticle art=
					articleMapper.selectByPrimaryKey(id);
			art.setTitle(title);
			art.setCategoryId(categoryId);
			art.setMemberName(author);
			articleMapper.updateByPrimaryKey(art);
		}
	 return true;
			 } 

	


	public List<CmsArticle> searchBy(Date begin, Date end, String key) {
	
		return articleMapper.selectBy(begin, end, key);
	}


	public int deleteById(String id) {
		return articleMapper.deleteByPrimaryKey(id);
	}


	public int batchDelete(String[] ids) {
		if(ids!=null&&ids.length>0) {
			return articleMapper.batchDeleteByIds(ids);
		}
		return 0;
	}


	
	

}
